<template>
	<el-card>
		<div class="second-content">
			<el-button type="primary" @click="dialogState = true">新增</el-button>
			<el-button type="primary" @click="publishHandle">发布</el-button>
			<el-button type="primary" @click="unPublishHandle"> 取消发布</el-button>
		</div>
		<el-table ref="multipleTableRef" :data="dataList">
			<el-table-column type="selection" width="55" />
			<el-table-column type="index" label="序号" width="55" align="center" />
			<el-table-column prop="questionnaireName" label="问卷名称" header-align="center" align="center" />
			<el-table-column prop="publishTime" label="发布时间" header-align="center" align="center" />
			<el-table-column prop="createByName" label="创建人" header-align="center" align="center" />
			<el-table-column prop="createTime" label="创建时间" header-align="center" align="center" />
			<el-table-column prop="publishStatus" label="状态" header-align="center" align="center" width="80">
				<template #default="scope">
					<el-tag v-if="scope.row.publishStatus === '1'" type="success">已发布</el-tag>
					<el-tag v-else type="danger">未发布</el-tag>
				</template>
			</el-table-column>
			<el-table-column label="操作" header-align="center" align="center " width="110">
				<template #default="scope">
					<el-icon :size="16" title="编辑" color="#1491FF" style="cursor: pointer; margin: 0 6px" @click="handleEdit(scope.row)">
						<Edit />
					</el-icon>
					<el-icon :size="16" title="删除" color="#f56c6c" style="cursor: pointer; margin: 0 6px" @click="handleDel(scope.row)">
						<Delete />
					</el-icon>
				</template>
			</el-table-column>
		</el-table>
		<el-pagination
			:current-page="state.pageNum"
			:page-size="state.pageSize"
			:total="state.total"
			layout="total, sizes, prev, pager, next, jumper"
			@size-change="handleSizeChange"
			@current-change="handleCurrentChange"
		>
		</el-pagination>
		<cmDialog v-model="dialogState" :modal-title="formData?.mainId == '' ? '新增' : '编辑'" model-width="700px">
			<el-form ref="formRef" :model="formData" :rules="formRules" label-width="100px">
				<el-form-item label="问卷名称" prop="questionnaireName">
					<el-input v-model="formData.questionnaireName" placeholder="请输入问卷名称" style="width: 420px; margin-right: 10px" />
					<el-button type="primary" @click="showAddQuestion = true">添加问题</el-button>
				</el-form-item>
				<el-table :data="formData.details">
					<el-table-column type="index" label="序号" width="55" align="center" />
					<el-table-column prop="questionnaireType" label="问题类型" header-align="center" align="center" width="100">
						<template #default="scope">
							<el-tag v-if="scope.row.questionnaireType === '1'" type="success">问答题</el-tag>
							<el-tag v-else type="danger">是非题</el-tag>
						</template>
					</el-table-column>
					<el-table-column prop="questionContent" label="问题" header-align="center" align="center" />
					<el-table-column label="操作" header-align="center" align="center" width="100">
						<template #default="scope">
							<el-icon
								:size="16"
								title="编辑"
								color="#1491FF"
								style="cursor: pointer; margin-left: 5px"
								@click="handleQuestionEdit(scope.row, scope.$index)"
							>
								<Edit />
							</el-icon>
							<el-icon :size="16" title="删除" color="#f56c6c" style="cursor: pointer; margin-left: 5px" @click="handleQuestionDel(scope.$index)">
								<Delete />
							</el-icon>
						</template>
					</el-table-column>
				</el-table>
			</el-form>
			<template #footer>
				<div class="dialog-foot">
					<el-button @click="dialogState = false">关闭</el-button>
					<el-button type="primary" @click="submitForm(formRef)">提交</el-button>
				</div>
			</template>
			<cmDialog v-model="showAddQuestion" modal-title="添加问题" model-width="600px">
				<el-form ref="questionRef" :model="questionData" :rules="questionRules" label-width="100px">
					<el-form-item label="问题类型" prop="questionnaireType">
						<el-radio-group v-model="questionData.questionnaireType">
							<el-radio :value="'1'">问答题</el-radio>
							<el-radio :value="'2'">是非题</el-radio>
						</el-radio-group>
					</el-form-item>
					<el-form-item label="问题" prop="questionContent">
						<el-input v-model="questionData.questionContent" placeholder="请输入问题内容" />
					</el-form-item>
				</el-form>
				<template #footer>
					<div class="dialog-foot">
						<el-button @click="showAddQuestion = false">关闭</el-button>
						<el-button type="primary" @click="submitQuestionForm(questionRef)">提交</el-button>
					</div>
				</template>
			</cmDialog>
		</cmDialog>
	</el-card>
</template>

<script setup lang="ts">
import { SetWenJuanAdd, SetWenJuanDel, SetWenJuanList, SetWenJuanPublish, SetWenJuanUnPublish } from '@/api/other'
import cmDialog from '@/components/cm-dialog/index.vue'
import type { FormInstance, FormRules, TableInstance } from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus'
import { onMounted, reactive, ref, watch } from 'vue'

interface FormState {
	mainId: string
	questionnaireName: string
	details: Question[]
}

interface Question {
	detailId: string
	questionnaireType: string
	questionContent: string
}

const state = reactive({
	pageNum: 1,
	pageSize: 10,
	total: 1,
	dataListLoading: false
})
const dataList = ref([])
const multipleTableRef = ref<TableInstance>()
const dialogState = ref(false)
const formData = ref<FormState>({
	mainId: '',
	questionnaireName: '',
	details: []
})
const formRef = ref<FormInstance>()
const formRules = reactive<FormRules>({
	questionnaireName: [{ required: true, message: '请输入问卷名称', trigger: 'blur' }]
})
const showAddQuestion = ref(false)
const questionRef = ref<FormInstance>()
const questionData = ref<Question>({
	detailId: '',
	questionnaireType: '1',
	questionContent: ''
})
const questionRules = reactive<FormRules>({
	questionnaireType: [{ required: true, message: '请选择问题类型', trigger: 'blur' }],
	questionContent: [{ required: true, message: '请输入问题内容', trigger: 'blur' }]
})
const editIndex = ref(-1)

watch(
	() => dialogState.value,
	val => {
		if (!val) {
			formData.value = {
				mainId: '',
				questionnaireName: '',
				details: []
			}
		}
	}
)

watch(
	() => showAddQuestion.value,
	val => {
		if (!val) {
			questionData.value = {
				detailId: '',
				questionnaireType: '1',
				questionContent: ''
			}
			editIndex.value = -1
		}
	}
)

const publishHandle = () => {
	const selectedRows = multipleTableRef.value.getSelectionRows()
	if (selectedRows.length == 0) {
		return ElMessage.error('请至少选择一个项目')
	}
	const ids = selectedRows.map(i => i.mainId)
	SetWenJuanPublish({
		ids: ids
	}).then(res => {
		ElMessage.success('发布成功')
		getDataList()
	})
}

const unPublishHandle = () => {
	const selectedRows = multipleTableRef.value.getSelectionRows()
	if (selectedRows.length == 0) {
		return ElMessage.error('请至少选择一个项目')
	}
	const ids = selectedRows.map(i => i.mainId)
	SetWenJuanUnPublish({
		ids: ids
	}).then(res => {
		ElMessage.success('发布成功')
		getDataList()
	})
}

const getDataList = () => {
	state.dataListLoading = true
	SetWenJuanList({
		pageNum: state.pageNum,
		pageSize: state.pageSize
	}).then(res => {
		state.dataListLoading = false
		dataList.value = res.data.list || []
		state.total = res.data.total || 0
	})
}

const handleCurrentChange = (val: number) => {
	state.pageNum = val
	getDataList()
}
const handleSizeChange = (val: number) => {
	state.pageSize = val
	state.pageNum = 1
	getDataList()
}

const handleEdit = (row: any) => {
	formData.value = {
		mainId: row.mainId,
		questionnaireName: row.questionnaireName,
		details: row.questions.map((i: any) => {
			return {
				detailId: i.detailId,
				questionnaireType: i.questionnaireType,
				questionContent: i.questionContent
			}
		})
	}
	dialogState.value = true
}

const handleDel = (row: any) => {
	ElMessageBox.confirm('此操作将删除该问卷, 是否继续?', '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning'
	})
		.then(() => {
			SetWenJuanDel(row.mainId).then(res => {
				ElMessage.success('操作成功！')
				getDataList()
			})
		})
		.catch(() => {})
}

const handleQuestionEdit = (row: any, index: number) => {
	questionData.value = {
		detailId: row.detailId,
		questionnaireType: row.questionnaireType,
		questionContent: row.questionContent
	}
	showAddQuestion.value = true
	editIndex.value = index
}

const handleQuestionDel = (index: number) => {
	ElMessageBox.confirm('此操作将删除该问题, 是否继续?', '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning'
	})
		.then(() => {
			formData.value.details.splice(index, 1)
		})
		.catch(() => {})
}

const submitForm = async (formEl: FormInstance | undefined) => {
	if (!formEl) {
		return
	}
	await formEl.validate((valid, fields) => {
		if (valid) {
			if (formData.value.details.length == 0) {
				ElMessage.error('请添加问题')
				return
			}
			SetWenJuanAdd(formData.value).then(res => {
				ElMessage.success('操作成功！')
				dialogState.value = false
				getDataList()
			})
		} else {
			if (!fields) {
				return
			}
		}
	})
}

const submitQuestionForm = async (formEl: FormInstance | undefined) => {
	if (!formEl) {
		return
	}
	await formEl.validate((valid, fields) => {
		if (valid) {
			if (editIndex.value == -1) {
				formData.value.details.push(questionData.value)
			} else {
				formData.value.details[editIndex.value] = questionData.value
			}
			showAddQuestion.value = false
		} else {
			if (!fields) {
				return
			}
		}
	})
}

onMounted(() => {
	getDataList()
})
</script>
<style scoped>
.top-main {
	display: flex;
}

.top-search {
	display: flex;
}

.top-btn {
	display: flex;
}

.second-content {
	display: flex;
	justify-content: flex-end;
	margin-bottom: 20px;
}

.dialog-foot {
	display: flex;
	justify-content: center;
	margin-bottom: 10px;
	padding-bottom: 20px;
}
</style>
